package com.xiaotu.LockDemo;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author xiaotu
 * @Description //TODO
 * @Date 2022/3/30 13:59
 * @ClassName TestLock01
 * @Version 1.0
 * 测试lock锁
 **/
public class TestLock01 {
    public static void main(String[] args) {
        TestLock02 testLock02 = new TestLock02();
        new Thread(testLock02, "00001").start();
        new Thread(testLock02, "00002").start();
        new Thread(testLock02, "00003").start();
    }
}

class TestLock02 implements Runnable {
    Integer ticketNums = 1000;
    //定义Lock锁
    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            //synchronized (TestLock02.class){
            try {
                lock.lock();//加锁
                if (ticketNums <= 0) {
                    break;
                } else {Thread.sleep(200);
                    System.out.println(Thread.currentThread().getName() + "购票,剩余" + --ticketNums + "张");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();//解锁
            }
            //  }
        }
    }
}
